package com.forg.mvc.core.handle;

import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.forg.mvc.core.RequestContext;
import com.forg.mvc.core.excception.InterceptorInterruptException;

public class InterceptorHandler extends AbstractHandler implements Comparable<InterceptorHandler>{
    
    private static final Logger logger = LoggerFactory.getLogger(InterceptorHandler.class);
    
    int priority = 0;
    
    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

    public InterceptorHandler(){
    }
    
    public InterceptorHandler(Object o,Method m,int priority){
        super(o,m);
        this.priority = priority;
    }
    

    @Override
    protected boolean doHandle() {
        
        try {
            Object ret = method.invoke(instance, new Object[0]);
            if(ret instanceof Boolean){
                return (Boolean)ret;
            }
            
        } catch (InvocationTargetException e) {
            
            Throwable targetException = e.getTargetException();
            
            if(targetException instanceof InterceptorInterruptException){
                try {
                    PrintWriter writer = RequestContext.getResponse().getResp().getWriter();
                    writer.write(targetException.getMessage());
                    writer.close();
                } catch (Exception e2) {
                }
            }
            
            logger.error("Interceptor exception:{}",e.getTargetException().getMessage());
            return false;
        }catch (Exception e) {
            logger.error("Interceptor exception:{}",e.getMessage());
            return false;
        }
        
        return true;
    }

    /**
     * 优先级比较
     * 优先级大的 越优先（排在前面）
     * 
     */
    @Override
    public int compareTo(InterceptorHandler o) {
        
        if(this.priority > o.priority)
            return -1;
        
        if(this.priority < o.priority){
            return 1;
        }
        
        return 0;
    }
    
    @Override
    public int hashCode(){
        return (this.instance.toString() + this.method.getName() + priority).hashCode();
    }
    
    @Override
    public boolean equals(Object o){
        if(o instanceof InterceptorHandler){
            InterceptorHandler i = (InterceptorHandler)o;
            return 
                    (this.instance.toString().equals(i.getInstance().toString()))
                    && this.method.getName().equals(i.getInstance().toString())
                    && this.priority == i.getPriority();
        }
        
        return false;
    }
    
}
